package com.company.dcm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.company.dcm.common.R;
import com.company.dcm.entity.Factory;
import com.company.dcm.service.FactoryService;
import com.company.dcm.utils.IdUtils;
import com.company.dcm.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/factory")
public class FactoryController {
    @Autowired
    private FactoryService factoryService;

    @PostMapping("/add")
    public R add(@RequestBody Factory factory){
        if(StringUtils.isNullOrEmpty(factory.getFactoryName()))return R.error("工厂名不可为空！");
        if(factoryService.count(new LambdaQueryWrapper<Factory>().eq(Factory::getFactoryName,factory.getFactoryName()))>0){
            return R.error("工厂名不可重复！");
        }

        factory.setFactoryId(IdUtils.getInstance().NextId());
        if(factoryService.save(factory)){
            return R.success("新增成功！");
        }
        return R.error("未知错误！");
    }

    @GetMapping("/list")
    public R list(){
        return R.success(factoryService.getBaseMapper().selectList(null));
    }

    @PostMapping("/delete")
    public R delete(@RequestBody Factory factory){
        if(factory.getFactoryId()==null)return R.error("工厂名不可为空！");
        if(factoryService.count(new LambdaQueryWrapper<Factory>().eq(Factory::getFactoryId,factory.getFactoryId()))==0){
            return R.error("工厂不存在！");
        }

        if(factoryService.remove(new LambdaQueryWrapper<Factory>().eq(Factory::getFactoryId,factory.getFactoryId()))){
            return R.success("删除成功！");
        }
        return R.error("未知错误！");
    }
}
